//
//  BillListTableViewController.swift
//  LGMusic
//
//  Created by 梁尚嘉 on 2017/3/22.
//  Copyright © 2017年 LimeGah. All rights reserved.
//

import UIKit
import Alamofire


class BillListTableViewController: BaseTableViewController,BillListTableCellDelegate {

    var BillList : [Bill]?
    public var billType:BillType?
    fileprivate var delegater:BillListDelegater?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.delegater = BillListDelegater.delegater(with: self.tableView)

        let urlString = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&type="+(self.billType?.type)!+"&callback=cb_list&format=json&method=baidu.ting.billboard.billList"
        let parameters = ["_t":(UInt)(NSDate().timeIntervalSince1970*1000),
                          "size":25,
                          "offset":0] as [String : Any]


        Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding.default, headers:nil).responseString { (response) in
            
            var string = response.value?.replacingOccurrences(of: "/**/cb_list(", with: "")
            let index = string?.index((string?.endIndex)!, offsetBy: -2)
            string = string?.substring(to: index!);
            self.BillList = [Bill].deserialize(from: string , designatedPath: "song_list") as! [Bill]?
            self.reload()
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.reload()
    }

    func reload() -> Void {
        SongFMDBHelper.getFavoriteSongs({ (favoriteSongs) in
            favoriteSongs.forEach({ (song) in
                let song_id = song.songId
                if self.BillList != nil {
                    for (index,billToUser) in self.BillList!.enumerated() {
                        let isFavorite = billToUser.song_id == song_id
                        if isFavorite {
                            self.BillList?[index].isFavorite = isFavorite
                            break;
                        }
                    }
                }
            })
            LGHUD.dismiss()
            self.delegater?.bills = self.BillList
        });
    }

}
